package com.yx.udp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.net.Uri;
import android.os.Bundle;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;

import android.view.SurfaceView;
import android.view.TextureView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaPlayer;
import org.videolan.libvlc.util.VLCVideoLayout;

import java.io.File;
import java.util.ArrayList;

public class MainActivity2 extends AppCompatActivity  {

    private static final String TAG = "VLC_RECORDER";
    private static final int PERMISSION_REQUEST_CODE = 100;

    private LibVLC libVLC;
    private MediaPlayer mediaPlayer;
    private VLCVideoLayout videoLayout;
    private Surface surface;
    private Button btnStart, btnStop;
    private TextView tvStatus;

    private boolean isRecording = false;
    private String outputPath;
    private EditText url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        // 初始化视图
        videoLayout = findViewById(R.id.surfaceView);
        url = findViewById(R.id.url);
        btnStart = findViewById(R.id.btnStart);
        btnStop = findViewById(R.id.btnStop);
        tvStatus = findViewById(R.id.tvStatus);

        // 设置Surface回调

        // 按钮事件
        btnStart.setOnClickListener(v -> startRecording());
        btnStop.setOnClickListener(v -> stopRecording());

        // 检查权限
        checkPermissions();

        // 设置输出路径
        outputPath = getOutputFilePath();
    }

    private void checkPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                    },
                    PERMISSION_REQUEST_CODE);
        } else {
            initVLC();
        }
    }

    private void initVLC() {
        try {
            ArrayList<String> options = new ArrayList<>();
            options.add("--rtsp-tcp");
            options.add("--network-caching=300");

            // Android 10+ 需要添加的选项
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                options.add("--audio-time-stretch"); // 解决音频拉伸问题
            }

            libVLC = new LibVLC(this, options);
            mediaPlayer = new MediaPlayer(libVLC);
            mediaPlayer.attachViews(videoLayout, null, false, false);

            // 设置事件监听器
            mediaPlayer.setEventListener(event -> {
                switch (event.type) {
                    case MediaPlayer.Event.Opening:
                        tvStatus.setText("状态: 连接中...");
                        break;
                    case MediaPlayer.Event.Playing:
                        tvStatus.setText("状态: 播放中");
                        break;
                    case MediaPlayer.Event.Buffering:
                        tvStatus.setText("状态: 录制中");
                        break;
                    case MediaPlayer.Event.EncounteredError:
                        tvStatus.setText("错误: ");
                        break;
                }
            });

        } catch (Exception e) {
            Log.e(TAG, "VLC初始化失败", e);
        }
    }

    private void startRecording() {
        if (isRecording) return;

        String rtspUrl = String.valueOf(url.getText());


        try {
            // 创建输出文件
            File outputFile = new File(outputPath);
            if (outputFile.exists()) {
                outputFile.delete();
            }

            Media media = new Media(libVLC, Uri.parse(rtspUrl));

            // 增强的录制选项
            String sout = "#duplicate{" +
                    "dst=display," + // 显示在布局上
                    "dst=standard{" +
                    "access=file," +
                    "mux=mp4," +
                    "dst='" + outputPath + "'," +
                    "sync" + // 确保音视频同步
                    "}}";

            media.addOption(":sout=" + sout);
            media.addOption(":sout-mux-caching=100"); // 设置复用器缓存

            mediaPlayer.setMedia(media);
            // 正确附加视图

//            mediaPlayer.detachViews();
            mediaPlayer.play();
            isRecording = true;
            btnStart.setEnabled(false);
            btnStop.setEnabled(true);

        } catch (Exception e) {
            Log.e(TAG, "录制启动失败", e);
        }
    }

    private void stopRecording() {
        if (!isRecording) return;

        try {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
            }

            isRecording = false;
            btnStart.setEnabled(true);
            btnStop.setEnabled(false);
            tvStatus.setText("状态: 录制完成");

            Toast.makeText(this, "视频已保存至: " + outputPath, Toast.LENGTH_LONG).show();

        } catch (Exception e) {
            Log.e(TAG, "停止录制失败", e);
        }
    }

    private String getOutputFilePath() {
        // 使用公共目录 (兼容Android 10+)
        File moviesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
        File outputDir = new File(moviesDir, "VLC_Recordings");

        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }

        return new File(outputDir, "recording_" + System.currentTimeMillis() + ".mp4").getAbsolutePath();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initVLC();
            } else {
                Toast.makeText(this, "需要存储权限才能录制视频", Toast.LENGTH_LONG).show();
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mediaPlayer != null) {
            // 重新附加视图
//            mediaPlayer.attachViews(videoLayout, null, false, false);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mediaPlayer != null) {
            // 分离视图（避免内存泄漏）
            mediaPlayer.detachViews();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.detachViews(); // 确保分离
            mediaPlayer.release();
        }
        if (libVLC != null) {
            libVLC.release();
        }
        if (videoLayout != null) {
            // 释放VLC视频布局
        }
    }

//    @Override
//    public void surfaceCreated(SurfaceHolder holder) {
//        surface = holder.getSurface();
//        if (mediaPlayer != null && surface != null) {
//            mediaPlayer.attachViews(surfaceView, null, false, false);
//        }
//    }
//
//    @Override
//    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
//        surface = holder.getSurface();
//    }
//
//    @Override
//    public void surfaceDestroyed(SurfaceHolder holder) {
//        surface = null;
//    }


}